import { Component } from '@angular/core';
import {AlertController, IonicPage, LoadingController, NavController, NavParams} from 'ionic-angular';
import {LocalStorProvider} from "../../providers/local-stor/local-stor";
import {ApiProvider} from "../../providers/api/api";
import {SourceViewProvider} from "../../providers/source-view/source-view";
import {ThemeableBrowserObject} from "@ionic-native/themeable-browser";
import {downloadInfo} from "../../modal/downloadInfo";
import {FileTransferObject,FileTransfer} from "@ionic-native/file-transfer";

/**
 * Generated class for the ResoursePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-resourse',
  templateUrl: 'resourse.html',
})
export class ResoursePage {
  user_id;
  resourceList;

  searchText=null;//搜索内容

  themeableBrowser:ThemeableBrowserObject;
  inTime;
  backTime;
  source_idStr;

  downloadInfo:downloadInfo[]=[];

  showSearchBar = false;

  constructor(public navCtrl: NavController, public navParams: NavParams,private storage:LocalStorProvider,public http:ApiProvider,public loadingCtrl:LoadingController,
    public browser:SourceViewProvider,private alertCtrl:AlertController,private transfer: FileTransfer,public souceview:SourceViewProvider) {
  }

  /**
   * 当页面加载的时候触发，仅在页面创建的时候触发一次，如果被缓存了，那么下次再打开这个页面则不会触发
   */
  ionViewDidLoad() {
    this.storage.getKey("user_id").then(val=>{
      this.user_id=val;
    })

    this.storage.getKey("downLoadInfo").then(val=>{
      this.downloadInfo=val;
    });
  }

  /**
   * 当进入页面时触发
   */
  ionViewDidEnter() {
    this.storage.getKey("user_id").then(val => {
      this.user_id = val;
    });

    this.storage.getKey("downLoadInfo").then(val=>{
      this.downloadInfo=val;
    });

    this.getAllResource();
  }

  /**
   * 获取全部资源列表
   */
  getAllResource()
  {
    let loading = this.loadingCtrl.create({
      content: '正在加载',
      showBackdrop: false
    });
    loading.present();
     this.http.post("/source/getResourcesList.do",{studentId:this.user_id,action:'up',createTime:'now'}).subscribe(item=>{
       if(item["Code"]=="11111111")
       {
         loading.dismiss();
         this.http.showToast(item["Message"],"bottom")
       }
       else
       {
         this.resourceList=item["probList"];

         //从storage中获取相应资源之前的下载状况（0-未下载  1-已下载（下载成功） 2-下载中 3-刚刚下载失败 4-上一次下载失败）
         for(let source of this.resourceList)
         {
           //讲义、PDF、视频获取下载状态
           if(source["source_type"]=="40005"||source["source_type"]=="40011"||source["source_type"]=="40009")
           {
             source["isCheck"]=this.getDownloadState(source["source_id"]);
           }
         }
         console.log(this.resourceList);
         loading.dismiss();
       }
     });
  }

  /**
   * 搜索
   * @param ev
   */
  search()
  {
    this.showSearchBar = !this.showSearchBar

    let loading = this.loadingCtrl.create({
      content: '正在加载',
      showBackdrop: false
    });
    loading.present();

    this.http.post("/source/getResourcesList.do",{studentId:this.user_id,action:'up',createTime:'now',source_name:this.searchText}).subscribe(item=>{
      if(item["Code"]=="11111111")
      {
        loading.dismiss();
        this.http.showToast(item["Message"],"bottom")
      }
      else
      {
        loading.dismiss();
        this.resourceList=item["probList"];

        //从storage中获取相应资源之前的下载状况（0-未下载  1-已下载（下载成功） 2-下载中 3-刚刚下载失败 4-上一次下载失败）
        for(let source of this.resourceList)
        {
          //讲义、PDF、视频获取下载状态
          if(source["source_type"]=="40005"||source["source_type"]=="40011"||source["source_type"]=="40009")
          {
            source["isCheck"]=this.getDownloadState(source["source_id"]);
          }
          else//???
          {
            source["isCheck"]=0;
          }
        }
      }
    });
  }

  /**
   * 下拉刷新
   * @param refresher
   */
  doRefresh(refresher) {
    let loading = this.loadingCtrl.create({
      content: '刷新中...',
      showBackdrop: false
    });
    loading.present();

    this.http.post("/source/getResourcesList.do",{studentId:this.user_id,action:'up',createTime:'now'}).subscribe(item=>{
      if(item["Code"]=="11111111")
      {
        loading.dismiss();
        this.http.showToast(item["Message"],"bottom")
      }
      else
      {
        setTimeout(() => {
          this.resourceList = item["probList"];

          //从storage中获取相应资源之前的下载状况（0-未下载  1-已下载（下载成功） 2-下载中 3-刚刚下载失败 4-上一次下载失败）
          for(let source of this.resourceList)
          {
            //讲义、PDF、视频获取下载状态
            if(source["source_type"]=="40005"||source["source_type"]=="40011"||source["source_type"]=="40009")
            {
              source["isCheck"]=this.getDownloadState(source["source_id"]);
            }
            else//???
            {
              source["isCheck"]=0;
            }
          }

          refresher.complete();
          loading.dismiss();
        },2000);
      }
    });
  }

  /**
   * 加载更多
   * @param infiniteScroll
   */
  doInfinite(infiniteScroll)
  {
    let lastTime;
    if(this.resourceList.length>0)
      lastTime=this.resourceList[this.resourceList.length-1].create_time;
    else
      lastTime='now';

    this.http.post("/source/getResourcesList.do",{studentId:this.user_id,action:'up',createTime:lastTime}).subscribe(item=>{
      if(item["Code"]=="11111111")
      {
        this.http.showToast(item["Message"],"bottom")
      }
      else
      {
        setTimeout(() => {
          if(item["probList"].length>0)
          {
            this.resourceList.push(item["probList"]);

            //从storage中获取相应资源之前的下载状况（0-未下载  1-已下载（下载成功） 2-下载中 3-刚刚下载失败 4-上一次下载失败）
            for(let source of this.resourceList)
            {
              //讲义、PDF、视频获取下载状态
              if(source["source_type"]=="40005"||source["source_type"]=="40011"||source["source_type"]=="40009")
              {
                source["isCheck"]=this.getDownloadState(source["source_id"]);
              }
              else//???
              {
                source["isCheck"]=0;
              }
            }
          }
          infiniteScroll.complete();   //当数据请求完成调用
        },500);
      }
    });
  }

  /**
   * 资源预览
   * @param path
   * @param title
   * @param sourceId
   * @param sourceType
   * @param source_id
   * @constructor
   */
  ViewSource(path,title,sourceId,sourceType,source_id,unit_id,teacher_id,class_type,course_class_id,isCheck,is_startAnswer)
  {
    this.source_idStr=source_id;
    this.inTime=Date.parse(new Date().toString());
    let url='';
    if(sourceType=="40003")//网页链接
    {
      url=path;
    }
    else if(sourceType=="40002"||sourceType=="40010"||sourceType=="40009")//案例、图片、视频
    {
      url=this.http.filePath+path;
    }
    else if(sourceType=="40005"||sourceType=="40011")//讲义和pdf
    {
      if(isCheck==0||isCheck==3||isCheck==4)
      {
        this.http.showToast("该类型资源不能在线预览，请下载后打开","bottom");
        return;
      }
      else
      {
        url=path;
      }
    }

    //之前没有查看过，则先调取查看接口，之后不再次调取
    //2018-07-02 新增需求 资源已开始可以记录查看资源记录，若资源已停止则不记录
    if(isCheck==0&&(sourceType!="40005"&&sourceType!="40011")&&is_startAnswer==1)
    {
      this.http.post("/source/checkSource.do",{teacherId:+teacher_id,studentId:this.user_id,inUnitId:unit_id,
        classCourseId:course_class_id,sourceId:sourceId,sourceSign:1,sourceType:sourceType,classType:class_type}).subscribe(item=>{
        if(item["Code"]=="11111111")
        {
          this.http.showToast(item["Message"],"bottom");
        }
      })
    }

    if(sourceType=="40009")
    {
      this.browser.showVideo(url);
    }
    else if(sourceType=="40002"||sourceType=="40010"||sourceType=="40003")
    {
      this.themeableBrowser=this.browser.showPage(url,title);

      //后退更新查看时长
      this.themeableBrowser.on("backPressed").subscribe(item=>{
        this.backTime=Date.parse(new Date().toString());
        let look_time=(this.backTime-this.inTime)/1000;

        //2018-07-02 新增需求 资源已开始可以记录查看资源时长，若资源已停止则不记录查看时长
        if(is_startAnswer==1)
        {
          this.updataLookTime(look_time);
        }
      });

      //关闭更新查看时长
      this.themeableBrowser.on("closePressed").subscribe(item=>{
        this.backTime=Date.parse(new Date().toString());
        let look_time=(this.backTime-this.inTime)/1000;

        //2018-07-02 新增需求 资源已开始可以记录查看资源时长，若资源已停止则不记录查看时长
        if(is_startAnswer==1)
        {
          this.updataLookTime(look_time);
        }
      });
    }
    else if((sourceType=="40005"||sourceType=="40011")&&isCheck==1)
    {
      this.souceview.openFile(url);
    }

    //资源未停止可记录查看记录，否则不记录查看记录
    if(is_startAnswer==1)
    {
      this.http.post("/source/checkSource.do",{teacherId:+teacher_id,studentId:this.user_id,inUnitId:unit_id,
        classCourseId:course_class_id,sourceId:sourceId,sourceSign:1,sourceType:sourceType,classType: class_type.toString()}).subscribe(item=>{
        if(item["Code"]=="11111111")
        {
          this.http.showToast(item["Message"],"bottom");
        }
        else
        {
          //计时
          this.inTime=Date.parse(new Date().toString());
        }
      })
    }
  }

  /**
   * 回写资源查看时长
   */
  updataLookTime(lookTime)
  {
    this.http.post("/exercise/updateLooktime.do",{studentId:this.user_id,sourceId:this.source_idStr,looktime:lookTime}).subscribe(item=>{
      if(item["Code"]=="11111111") {
        this.http.showToast(item["Message"], "bottom");
      }
    });
  }

  /**
   * 从缓存中获取下载相应学生相应资源的下载状态
   * @param sourceid
   * @returns {number}
   */
  getDownloadState(sourceid) {
    let flag=0;
    for (let item of this.downloadInfo) {
      if (item.studentId == +this.user_id && item.sourceId == +sourceid)
      {
        flag=item.state;
        break;
      }
    }
    return flag;
  }

  /**
   * 下载文档（讲义，pdf）
   * 首次？？下载文件时调用checksource接口
   * @param path
   * @param e
   * @constructor
   */
  downLoadFile(isCheck,path,e,sourceId,sourceType,index,unit_id,teacher_id,class_type,course_class_id,start_answer)
  {
    console.log(path);
    const fileTransfer: FileTransferObject = this.transfer.create();
    //阻止事件冒泡
    e.stopPropagation();

    //之前已下载过，询问是否重新下载？
    if(isCheck==1)
    {
      let confirm = this.alertCtrl.create({
        title: '温馨提示',
        message: '当前资源已存在，是否重新下载？',
        buttons: [
          {
            text: '取消',
            handler: () => {
            }
          },
          {
            text: '是',
            handler: () => {
              this.resourceList[index]["isCheck"]=2;
              let url=this.http.filePath+path;
              fileTransfer.download(url, this.souceview.getTargetPath() + path).then((entry) =>
              {
                this.resourceList[index]["isCheck"]=1;
                this.addDownLoadInfo(sourceId,1);
              }).catch((error)=>
              {
                this.resourceList[index]["isCheck"]=3;
                this.addDownLoadInfo(sourceId,4);
              });
            }
          }
        ]
      });
      confirm.present();
    }
    else if(isCheck==3||isCheck==4)
    {
      let confirm = this.alertCtrl.create({
        title: '温馨提示',
        message: '下载文件失败，是否重新下载？',
        buttons: [
          {
            text: '取消',
            handler: () => {
            }
          },
          {
            text: '是',
            handler: () => {
              this.resourceList[index]["isCheck"]=2;
              let url=this.http.filePath+path;

              fileTransfer.download(url, this.souceview.getTargetPath() + path).then((entry) =>
              {
                this.resourceList[index]["isCheck"]=1;
                this.addDownLoadInfo(sourceId,1);
              }).catch((error)=>
              {
                this.resourceList[index]["isCheck"]=3;
                this.addDownLoadInfo(sourceId,4);
              });
            }
          }
        ]
      });
      confirm.present();
    }
    else
    {
      this.resourceList[index]["isCheck"]=2;

      let url=this.http.filePath+path;
      fileTransfer.download(url, this.souceview.getTargetPath() + path).then((entry) =>
      {
        this.resourceList[index]["isCheck"]=1;
        this.addDownLoadInfo(sourceId,1);
      }).catch((error)=>
      {
        this.resourceList[index]["isCheck"]=3;
        this.addDownLoadInfo(sourceId,4);
      });

      //2018-07-02 新增需求 若资源为停止 则记录下载（查看）记录；若停止则不记录查看记录
      if(start_answer==1)
      {
        this.http.post("/source/checkSource.do",{teacherId:+teacher_id,studentId:this.user_id,inUnitId:unit_id,
          classCourseId:+course_class_id,sourceId:sourceId,sourceSign:1,sourceType:sourceType,classType:class_type.toString()}).subscribe(item=>{
          if(item["Code"]=="11111111")
          {
            this.http.showToast(item["Message"],"bottom");
          }
        })
      }
    }
  }

  /**
   * 添加下载记录（目前是按最后一次下载状态为准，每次替换之前的）
   * @param sourceId
   * @param state
   */
  addDownLoadInfo(sourceId,state)
  {
    let flag=0;
    for (let item of this.downloadInfo) {
      if (item.studentId == +this.user_id && item.sourceId == +sourceId) {
        flag = 1;
        item.state = state;
      }
    }

    if(flag==0)
    {
      this.downloadInfo.push({sourceId:sourceId,state:state,studentId:this.user_id});
    }

    this.storage.setKey("downLoadInfo",this.downloadInfo);
  }
}
